<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 1. 文件选择框 -->
    <input type="file" id="file1" />
    <!-- 2. 上传按钮 -->
    <button id="btnUpload">上传文件</button>
    <br />
    <!-- 3. 显示上传到服务器上的图片 -->
    <img src="" alt="" id="img" width="800" />

    <script>
      // let btnUpload = document.querySelector("#btnUpload");
      // btnUpload.addEventListener("click", function () {
      //   let files = document.querySelector("#file1").files;
      //   if (files.length <= 0) return alert("请选择要上传的文件");
      //   let fd = new FormData();
      //   fd.append("avatar", files[0]);
      //   let xhr = new XMLHttpRequest();
      //   xhr.open("POST", "http://www.liulongbin.top:3006/api/upload/avatar");
      //   xhr.send(fd);
      //   xhr.onreadystatechange = function () {
      //     if (xhr.readyState === 4 && xhr.status === 200) {
      //       let data = JSON.parse(xhr.responseText);
      //       console.log(data);
      //       if (xhr.status === 200) {
      //         document.querySelector("#img").src =
      //           "http://www.liulongbin.top:3006" + data.url;
      //       } else {
      //         alert("图片上传失败");
      //       }
      //     }
      //   };
      // });

      let upload = document.querySelector("#btnUpload");
      upload.addEventListener("click", function () {
        let files = document.querySelector("#file1").files;
        if (files.length <= 0) return alert("上传文件失败");
        let Form = new FormData();
        Form.append("avatar", files[0]);
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "http://www.liulongbin.top:3006/api/upload/avatar");
        xhr.send(Form);
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            if (xhr.status === 200) {
              document.querySelector("#img").src =
                "http://www.liulongbin.top:3006" + data.url;
            } else {
              alert("上传文件失败");
            }
          }
        };
      });
    </script>
  </body>
</html>
